/**
 * Project Name:b2c-app
 * File Name:TokenInterceptor.java
 * Package Name:cn.bluemobi.app.core.interceptor
 * Date:2016年1月21日下午4:21:50
 * Copyright (c) 2016, bluemobi.cn All Rights Reserved.
 *
 */

package cn.bluemobi.app.core.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.bluemobi.app.service.TokenService;
import cn.bluemobi.app.utils.JsonUtils;

/**
 * Description: 拦截需要登陆之后才能访问的接口 <br/>
 * Date: 2016年1月21日 下午4:21:50 <br/>
 * 
 * @author hut
 * @version
 * @see
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // String token = request.getParameter("token");
        // if (StringUtils.isEmpty(token)) {
        // Dto<Object> dto = new Dto<Object>();
        // dto.errorMsg("您太长时间没有操作，请重新登录");
        // dto.setStatus(2);
        // writeJson(response, dto);
        // return false;
        // }
        // if (token.length() < 32 || !validToken(token)) {
        // Dto<Object> dto = new Dto<Object>();
        // dto.errorMsg("您的登录令牌无效");
        // dto.setStatus(2);
        // writeJson(response, dto);
        // return false;
        // }
        // if (tokenService.validateToken(token) == null) {
        // Dto<Object> dto = new Dto<Object>();
        // dto.errorMsg("您太长时间没有操作，请重新登录");
        // dto.setStatus(2);
        // writeJson(response, dto);
        // return false;
        // }
        return true;
    }

    private boolean validToken(String token) {
        return tokenService.checkTokenSign(token);
    }

    private void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JsonUtils.toJson(obj));
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
